<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <button class="btn-back" @click="handleBack">返回</button>
        <text class="page-title">生产入库</text>
        <button class="btn-print" @click="handlePdaPrint">打印测试</button>
      </view>
    </view>

    <!-- 基本信息表单 -->
    <view class="info-form">
      <view class="form-item">
        <text class="form-label">单据日期</text>
        <picker
          class="form-picker"
          mode="date"
          :value="formData.inDate"
          @change="handleDateChange"
        >
          <view class="picker-content">
            <text>{{ formData.inDate }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      <view class="form-item">
        <text class="form-label">目标仓库</text>
        <view class="warehouse-display">{{
          currentWarehouse ? currentWarehouse.warehouseName : "请选择"
        }}</view>
      </view>
    </view>

    <!-- 统一扫码输入区域 -->
    <view class="scan-section">
      <view class="section-header">
        <view class="title-wrapper">
          <text class="section-title">待提交</text>
        </view>
      </view>
      
      <!-- 使用统一扫码输入组件 -->
      <ScanInput
        v-model="searchForm.searchCode"
        placeholder="请输入单据号或扫码"
        tip-text="达到5笔数据自动提交"
        :loading="isSearching"
        :on-scan-result="handleScanResult"
        :on-confirm="searchPackPrintRecords"
        ref="scanInputRef"
      />
    </view>

    <!-- 待提交表格 -->
    <view v-if="packPrintRecords.length > 0" class="material-table-section">
      <view class="table-body">
        <view class="table-row header">
          <view class="table-cell">选择</view>
          <view class="table-cell">钢种</view>
          <view class="table-cell">规格</view>
          <view class="table-cell">净重(KG)</view>
          <view class="table-cell">箱号</view>
          <view class="table-cell">轴号</view>
        </view>
        <view
          v-for="(item, index) in packPrintRecords"
          :key="index"
          class="table-row"
          :class="{
            selected: isRecordSelected(item),
          }"
          @click="toggleRecordSelection(item, index)"
        >
          <view class="table-cell">
            <text v-if="isRecordSelected(item)" class="check-icon">✓</text>
            <text v-else class="uncheck-icon">○</text>
          </view>
          <view class="table-cell">{{ item.steelGrade || "-" }}</view>
          <view class="table-cell">{{ item.spec || "-" }}</view>
          <view class="table-cell">{{
            (item.weightOfNet || 0).toFixed(3)
          }}</view>
          <view class="table-cell">{{ item.boxCode || "-" }}</view>
          <view class="table-cell">{{ item.axisCode || "-" }}</view>
        </view>
      </view>
    </view>

    <!-- 统计信息和操作按钮 -->
    <view class="material-table-section">
      <view class="statistics-section">
        <view class="stat-item">
          <text class="stat-label">选中记录数</text>
          <text class="stat-value">{{ selectedRecords.length }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">总重量</text>
          <text class="stat-value">{{ totalWeight.toFixed(3) }} KG</text>
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="action-bar">
        <view class="action-row">
          <button class="btn-reset" @click="resetForm">重置</button>
          <button class="btn-submit" @click="handleManualSubmit">提交</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { ProdStockInApi } from "@/api/warehouse/prodstockin";
// 导入统一扫码输入组件
import ScanInput from "@/components/ScanInput";

export default {
  name: "StockInNew",
  components: {
    ScanInput
  },
  data() {
    return {
      // 入库类型配置
      inTypeOptions: [{ value: "manual", label: "生产入库" }],
      inTypeIndex: 0,

      // 表单数据
      formData: {
        inType: "weigh",
        inDate: this.getCurrentDate(),
        warehouseId: "",
        warehouseName: "",
      },

      // 搜索表单
      searchForm: {
        searchCode: "",
      },

      // 查询状态
      isSearching: false,

      // 数据列表
      currentWarehouse: null,

      // 包装打印记录数据
      packPrintRecords: [], // 包装打印记录列表
      selectedRecords: [], // 选中的记录列表（支持多选）

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        startDate: "", // 开始日期
        endDate: "", // 结束日期
      },
    };
  },

  computed: {
    currentInType() {
      return this.inTypeOptions[this.inTypeIndex]?.value;
    },

    totalWeight() {
      // 根据选中的记录计算总重量
      const total = this.selectedRecords.reduce(
        (sum, item) => sum + (Number(item.weightOfNet) || 0),
        0
      );
      return Number(total.toFixed(3));
    },
  },

  mounted() {
    this.loadInitialData();
  },

  methods: {
    /**
     * 处理扫码结果（自定义处理）
     * 返回false可以阻止默认的搜索行为
     */
    handleScanResult(barcode) {
      console.log("扫码结果预处理:", barcode);
      
      // 这里可以添加扫码结果的预处理逻辑
      // 比如格式验证、数据转换等
      
      // 返回true继续执行默认搜索，返回false阻止默认搜索
      return true;
    },

    /**
     * 搜索包装打印记录
     */
    async searchPackPrintRecords(searchCode) {
      if (!searchCode || searchCode.trim() === '') {
        uni.showToast({
          title: '请输入查询内容',
          icon: 'none'
        });
        return;
      }

      this.isSearching = true;

      try {
        // 根据仓库类型和搜索内容确定查询参数
        let boxCode = searchCode || undefined;
        let axisCode = searchCode || undefined;
        
        // 当searchCode 包含SD开发的字符串时，按照大箱号查询，否则按照轴号查询,C 开头箱号
        if (
          searchCode.includes("SD") ||
          searchCode.includes("C") ||
          this.currentWarehouse?.warehouseName === "细丝"
        ) {
          axisCode = "";
        } else {
          boxCode = "";
        }

        const params = {
          boxCode: boxCode,
          axisCode: axisCode,
        };

        const res = await ProdStockInApi.getPackPrintRecord(params);

        if (res.code === 0) {
          const newRecords = res.data || [];

          // 依据返回的productType 判断 细丝按照箱号汇总，其他按照轴号汇总给packPrintRecords
          let processedRecords = [];
          if (
            this.currentWarehouse?.warehouseName === "细丝" ||
            searchCode.includes("C")
          ) {
            processedRecords = newRecords.reduce((acc, cur) => {
              const existing = acc.find((item) => item.boxCode === cur.boxCode);
              if (existing) {
                existing.weightOfNet = Number(
                  (existing.weightOfNet + cur.weightOfNet).toFixed(3)
                );
              } else {
                acc.push({ ...cur });
              }
              return acc;
            }, []);
          } else {
            processedRecords = newRecords;
          }

          this.packPrintRecords = processedRecords;

          // 检查是否达到自动提交条件
          this.checkAutoSubmit();

          uni.showToast({
            title: `查询成功，共${processedRecords.length}条记录`,
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: res.message || '查询失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error("查询包装打印记录失败:", error);
        uni.showToast({
          title: '查询失败',
          icon: 'error'
        });
      } finally {
        this.isSearching = false;
      }
    },

    /**
     * 检查是否达到自动提交条件
     */
    checkAutoSubmit() {
      if (this.packPrintRecords.length >= 5) {
        // 达到5笔数据，自动提交
        setTimeout(() => {
          this.handleManualSubmit();
        }, 1000);
      }
    },

    /**
     * 切换记录选择状态
     */
    toggleRecordSelection(item, index) {
      const existingIndex = this.selectedRecords.findIndex(
        (record) => record.id === item.id
      );

      if (existingIndex > -1) {
        // 如果已选中，则取消选择
        this.selectedRecords.splice(existingIndex, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedRecords.push(item);
      }
    },

    /**
     * 检查记录是否被选中
     */
    isRecordSelected(item) {
      return this.selectedRecords.some((record) => record.id === item.id);
    },

    /**
     * 处理手动提交
     */
    async handleManualSubmit() {
      if (this.selectedRecords.length === 0) {
        uni.showToast({
          title: '请先选择要提交的记录',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({ title: '提交中...' });

        // 构建提交数据
        const submitData = {
          warehouseId: this.currentWarehouse.warehouseId,
          warehouseName: this.currentWarehouse.warehouseName,
          records: this.selectedRecords.map(record => ({
            boxCode: record.boxCode,
            axisCode: record.axisCode,
            steelGrade: record.steelGrade,
            spec: record.spec,
            weightOfNet: record.weightOfNet
          }))
        };

        // 调用API提交数据
        const res = await ProdStockInApi.submitStockIn(submitData);

        if (res.code === 0) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });

          // 清空选中的记录
          this.selectedRecords = [];
          
          // 刷新查询结果
          if (this.searchForm.searchCode) {
            this.searchPackPrintRecords(this.searchForm.searchCode);
          }
        } else {
          uni.showToast({
            title: res.message || '提交失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error("提交失败:", error);
        uni.showToast({
          title: '提交失败',
          icon: 'error'
        });
      } finally {
        uni.hideLoading();
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.searchForm.searchCode = '';
      this.packPrintRecords = [];
      this.selectedRecords = [];
      
      // 清空扫码输入框
      if (this.$refs.scanInputRef) {
        this.$refs.scanInputRef.clearInput();
      }
      
      uni.showToast({
        title: '已重置',
        icon: 'success'
      });
    },

    /**
     * 处理返回按钮
     */
    handleBack() {
      if (this.selectedRecords.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未入库，请先提交入库或删除待入库数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空选中记录
              this.selectedRecords = [];
              // 返回上一页
              uni.navigateBack();
            }
          },
        });
      } else {
        // 没有数据，直接返回
        uni.navigateBack();
      }
    },

    /**
     * 处理打印测试
     */
    async handlePdaPrint() {
      try {
        const success = await this.pdaPrint("测试打印内容");
        if (success) {
          this.$modal.alert({
            content: "打印成功",
            title: "提示",
          });
        } else {
          this.$modal.alert({
            content: "打印失败，请检查打印机状态",
            title: "错误",
          });
        }
      } catch (error) {
        console.error("打印测试异常:", error);
        this.$modal.alert({
          content: "打印测试异常：" + error.message,
          title: "错误",
        });
      }
    },

    /**
     * 处理日期变更
     */
    handleDateChange(e) {
      const selectedDate = e.detail.value;
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      this.formData.inDate = `${selectedDate} ${hours}:${minutes}:${seconds}`;
    },

    /**
     * 获取当前日期
     */
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    /**
     * 加载初始数据
     */
    async loadInitialData() {
      try {
        // 加载当前用户仓库
        const warehouseRes = await this.getCurrentWarehouse();
        if (warehouseRes) {
          this.currentWarehouse = warehouseRes;
          this.formData.warehouseId = warehouseRes.warehouseId;
          this.formData.warehouseName = warehouseRes.warehouseName;
        }
      } catch (error) {
        console.error("加载初始数据失败:", error);
      }
    },

    /**
     * 获取当前用户仓库
     */
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }

      // 默认值
      return {
        warehouseId: "DEFAULT",
        warehouseName: "默认仓库",
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background-color: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn-back {
  padding: 10rpx 20rpx;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.page-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.btn-print {
  padding: 10rpx 20rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.info-form {
  background-color: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  width: 120rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.form-picker {
  flex: 1;
}

.picker-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.picker-arrow {
  color: #999;
}

.warehouse-display {
  flex: 1;
  padding: 16rpx 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.scan-section {
  background-color: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.section-header {
  margin-bottom: 20rpx;
}

.title-wrapper {
  text-align: center;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.material-table-section {
  background-color: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.table-body {
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  overflow: hidden;
}

.table-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.header {
    background-color: #f8f8f8;
    font-weight: bold;
  }
  
  &.selected {
    background-color: #e3f2fd;
  }
}

.table-cell {
  flex: 1;
  padding: 16rpx 10rpx;
  text-align: center;
  font-size: 24rpx;
  color: #333;
  border-right: 1rpx solid #e0e0e0;
  
  &:last-child {
    border-right: none;
  }
}

.check-icon {
  color: #4caf50;
  font-size: 28rpx;
  font-weight: bold;
}

.uncheck-icon {
  color: #ccc;
  font-size: 28rpx;
}

.statistics-section {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.stat-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.action-bar {
  padding: 20rpx 0;
}

.action-row {
  display: flex;
  gap: 20rpx;
}

.btn-reset {
  flex: 1;
  height: 80rpx;
  background-color: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  
  &:active {
    background-color: #e0e0e0;
  }
}

.btn-submit {
  flex: 1;
  height: 80rpx;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  
  &:active {
    background-color: #45a049;
  }
}
</style>